package com.liyao.protobuf.test.service;

import com.google.common.collect.ImmutableMap;
import io.grpc.stub.StreamObserver;

import java.util.Map;

public class MyRpcServiceImpl extends MyServiceGrpc.MyServiceImplBase {
 
    private final Map<Integer, String> map = ImmutableMap.<Integer, String>builder()
            .put(1, "v1")
            .put(2, "v2")
            .put(3, "v3")
            .put(4, "v4")
            .put(5, "v5")
            .build();
 
    @Override
    public void getByKey(MyRequest request, StreamObserver<MyResponse> responseObserver) {
        int key = request.getKeys(0);
        String value = map.getOrDefault(key, "null");
 
        responseObserver.onNext(MyResponse.newBuilder().setValue(value).build());
        responseObserver.onCompleted();
    }
 
    @Override
    public void getByKeyServerStream(MyRequest request, StreamObserver<MyResponse> responseObserver) {
        for (int key : request.getKeysList()) {
            String value = map.getOrDefault(key, "null");
            responseObserver.onNext(MyResponse.newBuilder().setValue(value).build());
        }
        responseObserver.onCompleted();
    }
 
    @Override
    public StreamObserver<MyRequest> getByKeyClientStream(StreamObserver<MyResponse> responseObserver) {
        return new StreamObserver<MyRequest>() {
            String values = "";
            @Override
            public void onNext(MyRequest myRequest) {
                int key = myRequest.getKeys(0);
                values += map.getOrDefault(key, "null");
            }
 
            @Override
            public void onError(Throwable throwable) {
 
            }
 
            @Override
            public void onCompleted() {
                responseObserver.onNext(MyResponse.newBuilder().setValue(values).build());
                responseObserver.onCompleted();
            }
        };
    }
 
    @Override
    public StreamObserver<MyRequest> getByKeyBiStream(StreamObserver<MyResponse> responseObserver) {
        return new StreamObserver<MyRequest>() {
            @Override
            public void onNext(MyRequest myRequest) {
                int key = myRequest.getKeys(0);
                String value = map.getOrDefault(key, "null");
                responseObserver.onNext(MyResponse.newBuilder().setValue(value).build());
            }
 
            @Override
            public void onError(Throwable throwable) {
 
            }
 
            @Override
            public void onCompleted() {
                responseObserver.onCompleted();
            }
        };
    }
}